package com.huanf.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.huanf.domain.WriteToExcelVo;
import com.huanf.service.WriteToExcelService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileOutputStream;
import java.util.List;

/**
 * @author: 35238
 * 功能: easyPoi-将数据库的数据写入到Excel表格
 * 时间: 2023-12-26 23:54
 */
@RestController
@Slf4j
public class WriteToExcelController {

    @Autowired
    private WriteToExcelService writeToExcelService;

    @GetMapping("/toExcel") //浏览器访问 http://localhost:8081/toExcel
    public void toExcel() throws Exception {

        //文件保存到哪里，还要指定文件名
        String PATH = "E:\\桌面\\Java-Ready\\conf\\Excel\\easyPoiToExcel.xlsx";

        //从数据库查询数据
        List<WriteToExcelVo> list = writeToExcelService.list();

        //上面那个list其实就可以直接用了，但是如果你想拿到数据库的数据之后，自己修改一下再插入到表格，那么可以用如下的Lambda表达式
        list.forEach(xxlist -> {
            xxlist.setAddress("我修改你地址啦");//只是秀一下Lambda表达式
        });

        //生成Excel
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("用户列表信息", "我是Sheet"), WriteToExcelVo.class, list);
        FileOutputStream fileOutputStream = new FileOutputStream(PATH);
        workbook.write(fileOutputStream);

        //关闭流
        fileOutputStream.close();
        workbook.close();
    }
}
